package com.hefan.pay.service;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.PaymentTypeEnum;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.pay.alipay.AlipayCore;
import com.hefan.common.pay.alipay.AlipayNotify;
import com.hefan.common.pay.alipay.Signature;
import com.hefan.common.pay.alipay.UtilDate;
import com.hefan.common.util.PayPropertiesUtils;
import com.hefan.pay.bean.PayExtendVo;
import com.hefan.pay.bean.ThridPartyNotifyVo;
import com.hefan.pay.bean.TradeLog;
import com.hefan.pay.dao.PayReqLogDao;
import com.hefan.pay.itf.ThridPartyPayCallService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by lxw on 2016/11/8.
 */
@Component("alipayWapPayService")
public class AlipayWapPayServiceImpl implements ThridPartyPayCallService {

    private Logger logger = LoggerFactory.getLogger(AlipayWapPayServiceImpl.class);

    private String RSA_PRIVATE_KEY1 = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJusnY2S8e8y3wcr\n" +
            "/FDXVjFQjOZVGH28jSfeG1OAyH4SKTXpglufVygYewCuHFiC2NI75KIvD3/sp5DI\n" +
            "lgD7R5JY0U0CbBmrBqkT5gesDQxUFoYZOKR5h03UAUN7VCmAe+1RsQsmt/xdHy2v\n" +
            "3K3SFmdH9Do726AVzrUjWL9SYHFFAgMBAAECgYAU9JmI0z0KC/kFyCAA6dvKa6Nr\n" +
            "5gyT8Gu38CgRh4Z1ohA2F6bamopq9VCpeMaMC6EQO8u9IUSe3cZ4sOewXiL2FItp\n" +
            "4kZXrg1W3apGsx6bby0C3nfin0QZtU4GwTi6p8fnPVl5b4ZMkaWZXCDdpio3w9bS\n" +
            "2DKZjP5Ae4WiA33RCQJBAMjsmH26Ni49QkV1N7ZcmDnx6p/bXYqLqZ1BrduObA8D\n" +
            "aAkbLlcWy6AuyQ3eyu5/P6ZeaD9mlC6NMs9VIrZOP28CQQDGWLVIJ+/Hn+Dxz1f1\n" +
            "EivaSifhSUfjAaYldgzadmhJ359OQJV0di61VNNRFP3JxJl/YnAbSnRwdd+ZiewW\n" +
            "XACLAkA15zNp14EdmpWi6LWPmPvF397gEAviVWGlrK8lzemzhWhtuPsPpi/uw15w\n" +
            "+CpdHYpH6d/x0mVCr+LHuMFdQ1TFAkBsEpesGj6XObD6cKyPVvhX94HlSeWGdjaO\n" +
            "QNVeD5hhcBxAKgaFL4Phv7dofZSO5LVyaDOHWzk4sbFE2pat1DFjAkEAo1TonGNv\n" +
            "Fj+hWniVv4U+0j8TSmxjE9Hti+4SQ7AhGZs2SzzIRHFe4aU8HikxRsyTgeSduDRb\n" +
            "/7naA9TUREzq3Q==";

    @Resource
    private PayReqLogDao payReqLogDao;

    @Override
    public ResultBean thridPartyPayCall(PaymentTypeEnum paymentTypeEnum, TradeLog tradeLog, PayExtendVo payExtendVo) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("app_id", PayPropertiesUtils.getString("alipay.wapPay.appId"));
            paramMap.put("method", PayPropertiesUtils.getString("alipay.wapPay.method"));
            paramMap.put("format", PayPropertiesUtils.getString("alipay.wapPay.format"));
            if(StringUtils.isNotBlank(payExtendVo.getReturnUrl())) {
                paramMap.put("return_url",payExtendVo.getReturnUrl());
            }
            paramMap.put("charset", PayPropertiesUtils.getString("alipay.inputCharset"));
            //发送请求的时间，格式"yyyy-MM-dd HH:mm:ss"	2014-07-24 03:07:50
            paramMap.put("timestamp", UtilDate.getDateFormatter());
            paramMap.put("version", PayPropertiesUtils.getString("alipay.wapPay.version"));
            paramMap.put("notify_url", PayPropertiesUtils.getString("alipay.wapPay.notifyUrl"));

            //业务对象
            Map<String, String> bizContentMap = new HashMap<String, String>();
            bizContentMap.put("body", GlobalConstants.PAY_PRODUCT_NAME);
            bizContentMap.put("subject",GlobalConstants.PAY_PRODUCT_NAME);
            bizContentMap.put("out_trade_no", payExtendVo.getOrderId());
            bizContentMap.put("seller_id",PayPropertiesUtils.getString("alipay.wapPay.partner"));
            bizContentMap.put("timeout_express", PayPropertiesUtils.getString("alipay.wapPay.timeoutExpress"));
            bizContentMap.put("total_amount", String.valueOf(payExtendVo.getPayAmount()));
            bizContentMap.put("product_code", PayPropertiesUtils.getString("alipay.wapPay.productCode"));
            bizContentMap.put("goods_type", PayPropertiesUtils.getString("alipay.wapPay.goodsType"));
            String biz_content = JSON.toJSONString(bizContentMap);
            paramMap.put("biz_content", biz_content);

            String sign_type =  PayPropertiesUtils.getString("alipay.wapPay.signType");
            paramMap.put("sign_type",sign_type);
            //去除空值
            Map<String,String> signMap = AlipayCore.paraAppFilter(paramMap);
            //生成签名
            String sign = Signature.buildRequestMysign(signMap,sign_type,RSA_PRIVATE_KEY1);
            System.out.println("---------sing:"+sign);
            sign = URLEncoder.encode(sign,"utf-8");
            signMap.put("sign", sign);
            //获取业务参数串
            //String payReqStr = PayPropertiesUtils.getString("alipay.wapPay.requestUrl") + URLEncoder.encode(AlipayCore.createLinkString(signMap),"utf-8");

            String payReqStr = PayPropertiesUtils.getString("alipay.wapPay.requestUrl") + AlipayCore.createLinkString(signMap);
            Map returnMap = new HashMap();
            returnMap.put("reqPayUrl", payReqStr);
            returnMap.put("orderId",payExtendVo.getOrderId());
            returnMap.put("payAmount",tradeLog.getPayAmount());
            returnMap.put("income",tradeLog.getIncome());
            returnMap.put("rewardFanpiao",tradeLog.getRewardFanpiao());
            returnMap.put("incomeAmount",tradeLog.getIncomeAmount());
            resultBean.setData(returnMap);
            //记录操作日志
            this.payReqLogDao.savePayReqLog(payExtendVo.getOrderId(), payExtendVo.getUserId(), PayPropertiesUtils.getString("alipay.wapPay.method"), paymentTypeEnum.getPaymentType(), payReqStr, "", resultBean.getCode());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ResultBean(ResultCode.UNSUCCESS,null);
        }
        return resultBean;
    }

    @Override
    public ResultBean thridPartyPayNotify(String orderId, ThridPartyNotifyVo thridPartyNotifyVo) {
        logger.info("AlipayWapPayServiceImpl----thridPartyPayNotify----begin");
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS, NOTFIY_EXCEPTION_IS_HANDLER);
        String tradeStatus = String.valueOf(thridPartyNotifyVo.getAlipayTradeStatus());
        try {
            Map<String, String> checkParamsMap = new HashMap<String,String>();
            Map requestParams = thridPartyNotifyVo.getAliPayRequestParamsMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                checkParamsMap.put(name, valueStr);
            }
            logger.info("AlipayWapPayServiceImpl----thridPartyPayNotify----notify---check---begin");
            if (AlipayNotify.verify(checkParamsMap,PayPropertiesUtils.getString("alipay.wapPay.signType"),PayPropertiesUtils.getString("alipay.wapPay.alipayPublicKey"))) { //验证响应请求正确
                logger.info("AlipayWapPayServiceImpl----thridPartyPayNotify----notify---check---true");
                if(!"TRADE_FINISHED".equals(tradeStatus) && !"TRADE_SUCCESS".equals(tradeStatus)) { //支付失败
                    resultBean = new ResultBean(ResultCode.PayAlipayNotifyIsPayFail.get_code(),ResultCode.PayAlipayNotifyIsPayFail.getMsg()+";返回误码："+tradeStatus, NOTFIY_EXCEPTION_IS_HANDLER);
                }
            } else {
                resultBean = new ResultBean(ResultCode.UNSUCCESS.get_code(),ResultCode.PayAlipayNotifyIsNotValidUrl.getMsg()+";返回码："+tradeStatus, NOTFIY_EXCEPTION_IS_NOT_HANDLER);
            }
            payReqLogDao.updatePayReqNotifyInfo(orderId,resultBean.getCode(),resultBean.getMsg(), JSON.toJSONString(checkParamsMap));
        }catch (Exception e) {
            logger.error(e.getMessage());
            resultBean = new ResultBean(ResultCode.UNSUCCESS,NOTFIY_EXCEPTION_IS_NOT_HANDLER);
        }
        logger.info("AlipayWapPayServiceImpl----thridPartyPayNotify----end:"+JSON.toJSONString(resultBean));
        return resultBean;
    }

   /* @Override
    public ResultBean thridPartyPayCall(PaymentTypeEnum paymentTypeEnum, TradeLog tradeLog, PayExtendVo payExtendVo) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS, null);
        try {
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("service",PayPropertiesUtils.getString("alipay.wapPay1.service"));
            paramMap.put("partner",PayPropertiesUtils.getString("alipay.wapPay1.partner"));
            paramMap.put("_input_charset",PayPropertiesUtils.getString("alipay.inputCharset"));
            paramMap.put("notify_url",PayPropertiesUtils.getString("alipay.wapPay1.notifyUrl"));
            if(StringUtils.isNotBlank(payExtendVo.getReturnUrl())) {
                paramMap.put("return_url",payExtendVo.getReturnUrl());
            }
            paramMap.put("out_trade_no",payExtendVo.getOrderId());
            paramMap.put("subject", GlobalConstants.PAY_PRODUCT_NAME);
            paramMap.put("payment_type", PayPropertiesUtils.getString("alipay.wapPay1.paymentType"));
            paramMap.put("total_fee", String.valueOf(payExtendVo.getPayAmount()));
            paramMap.put("seller_id", PayPropertiesUtils.getString("alipay.wapPay1.partner"));
            paramMap.put("body", GlobalConstants.PAY_PRODUCT_NAME);
            paramMap.put("it_b_pay", PayPropertiesUtils.getString("alipay.wapPay1.itBPay"));
            paramMap.put("app_pay", PayPropertiesUtils.getString("alipay.wapPay1.appPay"));
            paramMap.put("goods_type",PayPropertiesUtils.getString("alipay.scanCodePay.goodsType"));
            logger.info("thridPartyPayCall----thridPartyPayCall-----");
            //去除空值
            Map<String,String> signMap = AlipayCore.paraAppFilter(paramMap);
            //生成签名
            String sign = Signature.buildRequestMysign(signMap, PayPropertiesUtils.getString("alipay.wapPay1.signType"), PayPropertiesUtils.getString("alipay.wapPay1.md5Key"));
            signMap.put("sign",sign);
            logger.info("thridPartyPayCall----thridPartyPayCall-----sign="+sign);
            //获取业务参数串
            String payReqStr = PayPropertiesUtils.getString("alipay.wapPay1.requestUrl") + AlipayCore.createLinkString(signMap);
            logger.info("thridPartyPayCall----thridPartyPayCall-----payReqStr=" + payReqStr);
            Map returnMap = new HashMap();
            returnMap.put("reqPayUrl",payReqStr);
            returnMap.put("orderId",payExtendVo.getOrderId());
            returnMap.put("payAmount",tradeLog.getPayAmount());
            returnMap.put("income",tradeLog.getIncome());
            returnMap.put("rewardFanpiao",tradeLog.getRewardFanpiao());
            returnMap.put("incomeAmount",tradeLog.getIncomeAmount());
            resultBean.setData(returnMap);
            //记录操作日志
            this.payReqLogDao.savePayReqLog(payExtendVo.getOrderId(), payExtendVo.getUserId(), PayPropertiesUtils.getString("alipay.scanCodePay.service"), paymentTypeEnum.getPaymentType(), payReqStr, "", resultBean.getCode());


        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ResultBean(ResultCode.UNSUCCESS, null);
        }
        return resultBean;
    }

    @Override
    public ResultBean thridPartyPayNotify(String orderId, ThridPartyNotifyVo thridPartyNotifyVo) {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS, NOTFIY_EXCEPTION_IS_HANDLER);
        String tradeStatus = String.valueOf(thridPartyNotifyVo.getAlipayTradeStatus());
        try {
            Map<String, String> checkParamsMap = new HashMap<String,String>();
            Map requestParams = thridPartyNotifyVo.getAliPayRequestParamsMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                checkParamsMap.put(name, valueStr);
            }

            if (AlipayNotify.verify(checkParamsMap,PayPropertiesUtils.getString("alipay.wapPay1.signType"),PayPropertiesUtils.getString("alipay.wapPay1.md5Key"))) { //验证响应请求正确
                if(!"TRADE_FINISHED".equals(tradeStatus) && !"TRADE_SUCCESS".equals(tradeStatus)) { //支付失败
                    resultBean = new ResultBean(ResultCode.PayAlipayNotifyIsPayFail.get_code(),ResultCode.PayAlipayNotifyIsPayFail.getMsg()+";返回误码："+tradeStatus, NOTFIY_EXCEPTION_IS_HANDLER);
                }
            } else {
                resultBean = new ResultBean(ResultCode.UNSUCCESS.get_code(),ResultCode.PayAlipayNotifyIsNotValidUrl.getMsg()+";返回码："+tradeStatus, NOTFIY_EXCEPTION_IS_NOT_HANDLER);
            }
            payReqLogDao.updatePayReqNotifyInfo(orderId,resultBean.getCode(),resultBean.getMsg(), JSON.toJSONString(checkParamsMap));
        }catch (Exception e) {
            logger.error(e.getMessage());
            resultBean = new ResultBean(ResultCode.UNSUCCESS,NOTFIY_EXCEPTION_IS_NOT_HANDLER);
        }
        return resultBean;
    }*/

    @Override
    public ResultBean thridPartyPayNotifyParse(ThridPartyNotifyVo thridPartyNotifyVo) {
        return new ResultBean<ThridPartyNotifyVo>(ResultCode.SUCCESS, thridPartyNotifyVo);
    }

}
